package main

import (
	"github.com/astaxie/beego/logs"
	"os/exec"
	"os"
	"bufio"
	"io"
)

func main()  {
	execScript("/tmp/test.sh")
}


func execScript(script string) error {

	logs.Info("execScript begin")

	cmd := exec.Command("bash", script)

	// 是否需要将log返回给server ?

	f, _ := os.Create("out.log")
	//cmd.Stdout = f
	//cmd.Stderr = f

	defer f.Close()

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		logs.Error("execScript, error:", err)
		return err
	}

	stderr, err := cmd.StderrPipe()
	if err != nil {
		logs.Error("execScript, error:", err)
		return err
	}

	err = cmd.Start()
	//err := cmd.Run()
	if err != nil {
		logs.Error("execScript, error:", err)
		return err
	}

	reader := bufio.NewReader(stdout)
	reader2 := bufio.NewReader(stderr)

	go func() {
		//实时循环读取输出流中的一行内容
		for {
			line, err2 := reader.ReadString('\n')
			if err2 != nil || io.EOF == err2 {
				break
			}
			logs.Info(line)
			f.WriteString(line)
		}
	}()

	go func() {
		//实时循环读取输出流中的一行内容
		for {
			line, err2 := reader2.ReadString('\n')
			if err2 != nil || io.EOF == err2 {
				break
			}
			logs.Info(line)
			f.WriteString(line)
		}
	}()


	err = cmd.Wait()
	if err != nil {
		logs.Error("execScript, wait error:", err)
	}
	// 向server反馈脚本执行结果

	logs.Info("execScript over")
	return nil
}
